<?php

namespace App\Http\Controllers\Sing;

use App\Helpers\Tools;
use App\Http\Controllers\Controller;
use Intervention\Image\Facades\Image;

class SingController extends Controller
{
    public function compose()
    {
        // 获取参数
        $sex = request('sex');
        $tapeIndex = request('tapeIndex');
        $faceRectangle = request('faceRectangle');
        $posterPath = request('posterPath');

        // 定义路径
        $today = date('Y-m-d');
        $qid = uniqid();
        $fusePath = "./uploads/fuse/{$today}_$qid.jpg";
        $fuseErPath = "./uploads/fuse/er/{$today}_$qid.jpg";

        // 获取模板资源
        $templateUrl = "./templates/tape_{$tapeIndex}_{$sex}.png";
        $templateErUrl = "./templates/er/tape_{$tapeIndex}_{$sex}.png";
        $templateBase = Image::make($templateUrl)->encode('data-url')->encoded;
        $templateErBase = Image::make($templateErUrl)->encode('data-url')->encoded;
        $photoBase = Image::make($posterPath)->encode('data-url')->encoded; // TODO 如果要看人脸位置，注释这行显示下面的注释

//        $templateFace = ($this->face($templateBase)['faces'][0]['face_rectangle']);
//        $templateErFace = ($this->face($templateErBase)['faces'][0]['face_rectangle']);
//        dump($templateFace);
//        dd($templateErFace);
        if ($sex == 1) {
            if ($tapeIndex == 0) {
                $templateFaceRectangle = '555,297,172,172';
                $templateErFaceRectangle = '440,296,173,173';
            } else if ($tapeIndex == 1) {
                $templateFaceRectangle = '569,304,160,160';
                $templateErFaceRectangle = '454,305,159,159';
            } else if ($tapeIndex == 2) {
                $templateFaceRectangle = '506,295,174,174';
                $templateErFaceRectangle = '391,295,173,173';
            } else if ($tapeIndex == 3) {
                $templateFaceRectangle = '576,269,171,171';
                $templateErFaceRectangle = '460,268,172,172';
            } else if ($tapeIndex == 4) {
                $templateFaceRectangle = '570,298,170,170';
                $templateErFaceRectangle = '455,296,171,171';
            } else if ($tapeIndex == 5) {
                $templateFaceRectangle = '568,336,164,164';
                $templateErFaceRectangle = '453,335,165,165';
            }
        }

        if ($sex == 2) {
            if ($tapeIndex == 0) {
                $templateFaceRectangle = '586,302,160,160';
                $templateErFaceRectangle = '471,301,161,161';
            } else if ($tapeIndex == 1) {
                $templateFaceRectangle = '544,307,153,153';
                $templateErFaceRectangle = '429,307,153,153';
            } else if ($tapeIndex == 2) {
                $templateFaceRectangle = '561,280,187,187';
                $templateErFaceRectangle = '446,279,187,187';
            } else if ($tapeIndex == 3) {
                $templateFaceRectangle = '587,284,172,172';
                $templateErFaceRectangle = '472,285,171,171';
            } else if ($tapeIndex == 4) {
                $templateFaceRectangle = '587,306,166,166';
                $templateErFaceRectangle = '472,306,166,166';
            } else if ($tapeIndex == 5) {
                $templateFaceRectangle = '559,320,163,163';
                $templateErFaceRectangle = '444,319,164,164';
            }
        }


        // 获取图片rl位置
//        $templateFace = ($this->face($templateBase)['faces'][0]['face_rectangle']);
//        $mergeFaceInfo = ($this->face($photoBase)['faces'][0]['face_rectangle']);

        // 定义融合rl参数
//        $templateFaceRectangle = $templateFace['top'] . ',' . $templateFace['left'] . ',' . intval($templateFace['width']) . ',' . intval($templateFace['height']);
//        $mergeFaceRectangle = intval($mergeFaceInfo['top']) . ',' . intval($mergeFaceInfo['left']) . ',' . ($mergeFaceInfo['width']) . ',' . ($mergeFaceInfo['height']);

        $res = $this->fuse($templateBase, $templateFaceRectangle, $photoBase, $faceRectangle);
        $erRes = $this->fuse($templateErBase, $templateErFaceRectangle, $photoBase, $faceRectangle);

        if (isset($res['result'])) {
            $img = Image::make($res['result']);
            $erImg = Image::make($erRes['result']);

            // 添加头像和昵称
//            $avatarImg = Image::make($avatarUrl)->resize(130, 130);
//            $img->insert($avatarImg, 'top-left', 50, 82);
//            $img->text($nickname, 116, 230, function ($font) {
//                $font->file(public_path('grades') . '/fonts/PingFangBold.ttf');
//                $font->size(19);
//                $font->align('center');
//                $font->valign('middle');
//                $font->color('#fff');
//            });

            // 保存图片
            $res = $img->save($fusePath);
            $erImg->save($fuseErPath);

            if ($res) {
                if ($res) {
                    $data = [
                        'posterPath' => $fusePath,
                        'posterErPath' => $fuseErPath
                    ];

                    // 返回数据
                    return Tools::setData($data);
                }
            }
        }

        return Tools::error('请上传更清晰的图片');
    }

    // 合成照片
    public function compose2()
    {
        $photoBase = request('photoBase');
        $sex = request('sex');
        $tapeIndex = request('tapeIndex');
        $avatarUrl = request('avatarUrl');
        $nickname = request('nickname');

        $today = date('Y-m-d');
        $qid = uniqid();
        $facePath = "./uploads/face/{$today}_$qid.jpg";
        $posterPath = "./uploads/poster/{$today}_$qid.jpg";
        $tapePath = "./templates/tape_{$tapeIndex}_{$sex}.png";

        // 根据不同类型设置不同的位置
        if ($sex == 1) {
            if ($tapeIndex == 0) {
                $faceImgX = 322;
                $faceImgY = 393;
                $facePathW = 129;
                $facePathH = 138;
            } else if ($tapeIndex == 1) {
                $faceImgX = 313;
                $faceImgY = 367;
                $facePathW = 108;
                $facePathH = 128;
            } else if ($tapeIndex == 2) {
                $faceImgX = 310;
                $faceImgY = 425;
                $facePathW = 113;
                $facePathH = 125;
            } else if ($tapeIndex == 3) {
                $faceImgX = 349;
                $faceImgY = 408;
                $facePathW = 112;
                $facePathH = 142;
            }
        }

        if ($sex == 2) {
            if ($tapeIndex == 0) {
                $faceImgX = 315;
                $faceImgY = 397;
                $facePathW = 120;
                $facePathH = 115;
            } else if ($tapeIndex == 1) {
                $faceImgX = 314;
                $faceImgY = 598;
                $facePathW = 147;
                $facePathH = 167;
            } else if ($tapeIndex == 2) {
                $faceImgX = 309;
                $faceImgY = 385;
                $facePathW = 120;
                $facePathH = 128;
            } else if ($tapeIndex == 3) {
                $faceImgX = 375;
                $faceImgY = 385;
                $facePathW = 133;
                $facePathH = 132;
            }
        }


        preg_match('/^(data:\s*image\/(\w+);base64,)/', $photoBase, $result);

        $photoBase = str_replace($result[1], '', $photoBase);

        $token = $this->accessToken()['access_token'];

        $url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' . $token;
        $bodys = "{\"image\":\"$photoBase\",\"image_type\":\"BASE64\",\"face_field\":\"faceshape,facetype\"}";
        $faceInfo = json_decode($this->requestPost($url, $bodys), true);

        if ($faceInfo) {
            $local = $faceInfo['result']['face_list'][0]['location'];

            Image::make($photoBase)->crop((int)$local['width'], (int)$local['height'], (int)$local['left'], (int)$local['top'])->save($facePath);

            $img = Image::canvas(750, 1250);
            $faceImg = Image::make($facePath)->resize($facePathW, $facePathH)->encode('data-url');
            $avatarImg = Image::make($avatarUrl)->resize(130, 130);

            // 美白图片
            $whiteningFaceBase = $this->whitening($faceImg->encoded)['result'];

            $avatarImg->save('./uploads/aa.jpg');
            $img->insert($whiteningFaceBase, 'top-left', $faceImgX, $faceImgY);
            $img->insert($tapePath, 'top-left', 0, 0);
            $img->insert($avatarImg, 'top-left', 50, 82);

            $img->resize(750, 1250)->save($posterPath);

            // $img->resize(375, 625)->save('test3.jpg');
            $data['posterPath'] = $posterPath;

            return $resource = [
                'error' => 0,
                'status' => 200,
                'data' => $data
            ];

        } else {

            return $resource = [
                'error' => 1,
                'status' => 200,
                'message' => '请上传清晰一点的照片',
                'data' => []
            ];

        }
    }

    public function accessToken()
    {
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type'] = 'client_credentials';
        $post_data['client_id'] = 'qzA4zbL9k0GLgci3boqXveBM';
        $post_data['client_secret'] = '0MjS6lEdGrN05IDtcWBFj4WsDoidZV1E';
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);

        $res = $this->requestPost($url, $post_data);

        return json_decode($res, true);
    }

    // TODO 1111
    public function photo()
    {
        $photoBase = request('photoBase', '');
        $today = date('Y_m_d_H');
        $qid = uniqid();
        $posterPath = "./uploads/poster/{$today}_$qid.png";

        // 获取rl图片位置
        $photoFaceInfo = $this->face($photoBase);

        if (isset($photoFaceInfo['faces'][0]['face_rectangle'])) {
            $photoFace = $photoFaceInfo['faces'][0]['face_rectangle'];
            $photoFaceAttributes = $photoFaceInfo['faces'][0]['attributes'];
            $photoFaceRectangle = intval($photoFace['top']) . ',' . intval($photoFace['left']) . ',' . ($photoFace['width']) . ',' . ($photoFace['height']);

            // 保存图片
            $res = Image::make($photoBase)->save($posterPath);
//            $res = Image::make($photoBase)->encode('png', 70);
//            imagepng(imagecreatefromstring(file_get_contents($posterPath)), $posterPath);
//dd($res);
            if ($res) {
                if ($photoFaceAttributes['blur']['blurness']['value'] < 1 && $photoFaceAttributes['facequality']['value'] > 80) {
                    if ($photoFaceAttributes['eyestatus']['left_eye_status']['occlusion'] < 10 && $photoFaceAttributes['eyestatus']['right_eye_status']['occlusion'] < 10) {
                        $data = [
                            'faceRectangle' => $photoFaceRectangle,
                            'posterPath' => $posterPath,
                            'attributes' => $photoFaceAttributes
                        ];

                        // 返回数据
                        return Tools::setData($data);
                    } else {
                        return Tools::error('您的眼睛被挡住了哦！请上传清晰的人脸五官图片');
                    }

                } else {
                    return Tools::error('这张照片有点模糊哦！请上传清晰的人脸五官图片');
                }
            }
        }

        return Tools::error('请上传清晰的人脸五官图片');
    }

    //
    public function whitening($base64)
    {
        $url = 'https://api-cn.faceplusplus.com/facepp/beta/beautify';
        $params = [
            'api_key' => 'LO2ijypegqS5_QTbQHU8BTev65pywXL8',
            'api_secret' => 'JVhdkG4zCInSVKCpi6sbyfOEdINdyhel',
            'image_base64' => $base64,
            'whitening' => 100,
            'smoothing' => 100
        ];

        return json_decode($this->requestPost($url, $params), true);
    }

    //
    public function fuse($templateBase, $templateRectangle, $mergeBase, $mergeRectangle)
    {
        $url = 'https://api-cn.faceplusplus.com/imagepp/v1/mergeface';
        $params = [
            'api_key' => 'LO2ijypegqS5_QTbQHU8BTev65pywXL8',
            'api_secret' => 'JVhdkG4zCInSVKCpi6sbyfOEdINdyhel',
            'template_base64' => $templateBase,
            'template_rectangle' => $templateRectangle,
            'merge_base64' => $mergeBase,
            'merge_rectangle' => $mergeRectangle,
            'merge_rate' => 75
        ];

        return json_decode($this->requestPost($url, $params), true);

    }

    // 人脸识别
    public function face($imgSource)
    {
        $url = 'https://api-cn.faceplusplus.com/facepp/v3/detect';
        if (strlen($imgSource) > 300) {
            $params = [
                'api_key' => 'LO2ijypegqS5_QTbQHU8BTev65pywXL8',
                'api_secret' => 'JVhdkG4zCInSVKCpi6sbyfOEdINdyhel',
                'image_base64' => $imgSource,
                'return_attributes' => 'blur,facequality,eyestatus'
            ];
        } else {
            $params = [
                'api_key' => 'LO2ijypegqS5_QTbQHU8BTev65pywXL8',
                'api_secret' => 'JVhdkG4zCInSVKCpi6sbyfOEdINdyhel',
                'image_url' => $imgSource,
                'return_attributes' => 'blur,facequality'
            ];
        }

        return json_decode($this->requestPost($url, $params), true);
    }

    /**
     * 模拟post进行url请求
     * @param string $url
     * @param string $param
     */
    function requestPost($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }

}
